package cn.itcast.bos.action;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class AreaAction extends BaseAction<Area> {

	private static final long serialVersionUID = 1L;
//使用模型驱动：BaseAcrion<Area> 代替
//	private Area area = new Area();
//	
//	@Override
//	public Area getModel() {
//		return area;
//	}
	
	private File file;//表示上传的文件
	private String fileContentType;//：表示获取上传文件的类型
	private String fileFileName;//表示获取上传的文件名
	
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	@Autowired(required=true)
	private AreaService areaService;
	

	public void setFile(File file) {
		this.file = file;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	@Action(value="area_batchImport")
	public String batchImport() throws Exception{
		// 基于.xls 格式解析 HSSF
		// 1、 加载Excel文件对象
		List<Area> areas = new ArrayList<Area>();
		
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 2、 读取一个sheet
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);//获取第一个sheet对象,索引从零开始
		// 3、 读取sheet中每一行，一行数据 对应 一个区域对象
		for (Row row : sheet) {
			//第一行跳过:表格信息、非数据
			if(row.getRowNum()==0){
				continue;
			}
			// 跳过空值的行，要求此行作废
			//表示第一个单元格：row.getCell(0)
			if(row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())){
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());//区域编号
			area.setProvince(row.getCell(1).getStringCellValue());//省份
			area.setCity(row.getCell(2).getStringCellValue());//城市
			area.setDistrict(row.getCell(3).getStringCellValue());//区域
			area.setPostcode(row.getCell(4).getStringCellValue());//邮编
			
			/** 基于pinyin4j生成城市编码和简码 */
			//获取省市区
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			
			//去除省市县的最后一个字
			province = province.substring(0, province.length()-1);	//去除"省"
			city = city.substring(0, city.length()-1);				//去除"市"
			district = district.substring(0, district.length()-1);	//去除"县"
			
			//简码
			String[] headArray = PinYin4jUtils.getHeadByString(province+city+district);
			//使用StringBuffer把数组拼接成字符串
			StringBuffer sb = new StringBuffer();
			for (String headStr : headArray) {
				sb.append(headStr);
			}
			
			String shortcode = sb.toString();//首字母简码

			//城市编码
			String citycode = PinYin4jUtils.hanziToPinyin(city, "");
			
			area.setCitycode(citycode);
			area.setShortcode(shortcode);
			//添加到集合中
			areas.add(area);
		}
		
		// 调用业务层
		areaService.saveAreas(areas);
		
		return NONE;
	} 
	
	/**
	 * 有条件分页查询
	 * */
	
	@Action(value="area_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows);
		/**带条件的查询*/
		Specification<Area> specification = new Specification<Area>(){

			@Override
			// Root 用于获取属性字段，CriteriaQuery可以用于简单条件查询，CriteriaBuilder 用于构造复杂条件查询（多表）
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				Predicate predicate = null;
				List<Predicate> list = new ArrayList<Predicate>();
				if(StringUtils.isNoneBlank(model.getProvince())){
					Predicate p = cb.like(root.get("province").as(String.class),"%" + model.getProvince() + "%");//模糊查询提交的省信息
					list.add(p);
				}
				if(StringUtils.isNoneBlank(model.getCity())){
					Predicate p = cb.like(root.get("city").as(String.class), "%" + model.getCity() + "%");//模糊查询提交的市信息
					list.add(p);
				}
				if(StringUtils.isNoneBlank(model.getDistrict())){
					Predicate p = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");//模糊查询提交的县信息
					list.add(p);
				}
				
				if(list != null && list.size() > 0){
					Predicate [] p = new Predicate[list.size()];
					predicate = cb.and(list.toArray(p));
				}
				
				return predicate;
			}
		};
		//带有条件的查询
		Page<Area> pagedata = areaService.findPageDate(specification,pageable);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", pagedata.getTotalElements());
		map.put("rows", pagedata.getContent());
		
		ServletActionContext.getContext().getValueStack().push(map);
		
		return SUCCESS;
	}
	
}
